<template>
  <div class="list-pages white-bg">
    <div class="search-form-box">
      <a-form
        :model="formState"
        name="horizontal_login"
        :label-col="labelCol"
        autocomplete="off"
        @finish="onFinish"
      >
        <a-row :gutter="[16, 16]">
          <a-col :xs="24" :sm="24" :md="12" :lg="6" :xl="6" v-show="expand">
            <a-form-item label="名称" name="name">
              <a-input
                v-model:value="formState.name"
                placeholder="请输入实验名称"
              >
              </a-input>
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="12" :lg="6" :xl="6" v-show="expand">
            <a-form-item label="分类" name="experiment_category_idArray">
              <a-select
                v-model:value="formState.experiment_category_idArray"
                :options="categoryOptions"
                mode="multiple"
                placeholder="请选择分类"
              />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="12" :lg="6" :xl="6" v-show="expand">
            <a-form-item label="类型" name="experiment_type_idArray">
              <a-select
                v-model:value="formState.experiment_type_idArray"
                :options="typeOptions"
                mode="multiple"
                placeholder="请选择"
              />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="12" :lg="6" :xl="6" v-show="expand">
            <a-form-item label="状态" name="experiment_status_idArray">
              <a-select
                v-model:value="formState.experiment_status_idArray"
                :options="statusOptions"
                mode="multiple"
                placeholder="请选择"
              />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="12" :lg="6" :xl="6" v-show="expand">
            <a-form-item label="付费性质" name="experiment_pay_type_idArray">
              <a-select
                v-model:value="formState.experiment_pay_type_idArray"
                :options="payTypeOptions"
                mode="multiple"
                placeholder="请选择"
              />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12" v-show="expand">
            <a-form-item label="更新时间" name="dateRange">
              <a-range-picker v-model:value="formState.dateRange" />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="12" :lg="6" :xl="6">
            <a-form-item>
              <div class="search-btn-box" :class="{ pt: expand }">
                <a-button
                  :icon="h(SearchOutlined)"
                  type="primary"
                  html-type="submit"
                  class="search-btn"
                  >查询</a-button
                >
                <a-button
                  :icon="h(ReloadOutlined)"
                  class="reset-btn"
                  @click="resetForm"
                  >清空</a-button
                >
                <a
                  class="expand-btn"
                  style="font-size: 12px; margin-left: 12px"
                  @click="expand = !expand"
                >
                  <template v-if="expand">
                    <UpOutlined />
                  </template>
                  <template v-else>
                    <DownOutlined />
                  </template>
                  {{ expand ? "收起查询" : "展开查询" }}
                </a>
              </div>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <div class="opt-button-box">
      <a-button type="primary" class="btn" @click="handleAdd">
        <img src="/icons/common/icon-add.png" class="icon" />新增</a-button
      >
      <a-button
        type="primary"
        class="btn"
        @click="handleExport"
        :disabled="selectedRowKeys.length === 0"
      >
        <img src="/icons/common/icon-export.png" class="icon" />批量导出 ({{
          selectedRowKeys.length
        }})</a-button
      >
      <a-button
        v-if="selectedRowKeys.length > 0"
        class="btn"
        @click="clearSelection"
      >
        清空选择</a-button
      >
      <a-button
        type="primary"
        danger
        class="btn"
        @click="handleDeleteOfflineExperiments"
        :loading="deleteLoading"
      >
        <template #icon>
          <DeleteOutlined />
        </template>
        一键彻底删除下架实验</a-button
      >
    </div>
    <div class="table-wrapper" ref="tableRef">
      <a-table
        class="table-box"
        row-key="experiment_id"
        :columns="columns"
        :dataSource="tableData"
        :row-class-name="
          (_record, index) => (index % 2 === 1 ? 'table-striped' : null)
        "
        sticky
        :scroll="{ y: true, x: 1100 }"
        :pagination="pagination"
        @change="onChange"
        :row-selection="rowSelection"
      >
        <template #bodyCell="{ column, record }">
          <!-- <template v-if="column.thumb_url">
            <img :src="record.thumb_url" alt="" />
          </template> -->
          <template v-if="column.dataIndex == 'enabled'">
            {{ record.enabled ? "上架" : "下架" }}
          </template>
          <template v-if="column.dataIndex == 'operation'">
            <a-button type="link" class="link" @click="handleDetail(record)">
              查看
            </a-button>
            <a-button type="link" class="link" @click="handleEdit(record)">
              编辑
            </a-button>

            <a-popconfirm
              v-if="!record.enabled"
              title="确认上架?"
              @confirm="handleDelte(record, true)"
            >
              <a-button type="link"> 上架 </a-button></a-popconfirm
            >
            <a-popconfirm
              v-if="record.enabled"
              title="确认下架?"
              @confirm="handleDelte(record, false)"
            >
              <a-button type="link" class="link">下架 </a-button></a-popconfirm
            >
          </template>
        </template>
      </a-table>
    </div>
  </div>
</template>
<script setup>
import api from "@/api";
import AP from "@/api/user";
import { useGlobalStore } from "@/store/modules/global";
import {
  DeleteOutlined,
  DownOutlined,
  ReloadOutlined,
  SearchOutlined,
  UpOutlined,
} from "@ant-design/icons-vue";
import { message, Modal } from "ant-design-vue";
import { computed, h, onMounted, onUnmounted, ref } from "vue";
import { useRouter } from "vue-router";
const store = useGlobalStore();
const router = useRouter();
const labelCol = { style: { width: "80px" } };

const formState = ref({});
const resetForm = () => {
  formState.value = {
    name: "",
    status: [],
  };

  onFinish(undefined);
};
const windowWidth = ref(window.innerWidth);
const categoryOptions = ref([]);
const typeOptions = ref([]);
const statusOptions = ref([]);
const payTypeOptions = ref([]); //experiment_pay_type_idArray
const expand = ref(true);
const deleteLoading = ref(false);
onMounted(() => {
  fetchOptions();
  windowWidth.value = window.innerWidth;
  if (windowWidth.value > 768) {
    expand.value = true;
  } else {
    expand.value = false;
  }
  window.addEventListener("resize", () => {
    windowWidth.value = window.innerWidth;
    if (windowWidth.value > 768) {
      expand.value = true;
    } else {
      expand.value = false;
    }
  });
});
const fetchOptions = () => {
  api
    .apiExperimentCategoryOptionsPost({})
    .then(({ data }) => (categoryOptions.value = data));
  api
    .apiExperimentTypeOptionsPost({})
    .then(({ data }) => (typeOptions.value = data));
  api
    .apiExperimentStatusOptionsPost({})
    .then(({ data }) => (statusOptions.value = data));
  api
    .apiExperimentPayTypeOptionsPost({})
    .then(({ data }) => (payTypeOptions.value = data));

  onFinish(undefined);
};
onUnmounted(() => {
  window.removeEventListener("resize", () => {});
});

const response = ref({});
function onFinish(args) {
  console.log("Success:", args);
  // 清空选择状态
  selectedRowKeys.value = [];
  selectedRows.value = [];

  // 将name字段改为keyword传给后端
  const requestArgs = {
    ...args,
    current: current.value,
    pageSize: pageSize.value,
  };
  if (requestArgs && requestArgs.name) {
    requestArgs.keyword = requestArgs.name;
    delete requestArgs.name;
  }

  api
    .apiExperimentPagedListPost({
      args: requestArgs,
    })
    .then((res) => {
      tableData.value = res.data.data;
      response.value = res.data;
    });
}
const tableData = ref([]);
const selectedRowKeys = ref([]);
const selectedRows = ref([]);

// 行选择配置
const rowSelection = {
  selectedRowKeys: selectedRowKeys,
  onChange: (keys, rows) => {
    selectedRowKeys.value = keys;
    selectedRows.value = rows;
    console.log("选中的行:", keys, rows);
  },
  onSelectAll: (selected, rows, changeRows) => {
    console.log("全选状态:", selected, rows, changeRows);
  },
};

const columns = ref([
  {
    dataIndex: "name",
    title: "名称",
    ellipsis: true,
    width: 180,
  },
  {
    dataIndex: "experiment_category_name",
    title: "分类",
    width: 110,
  },
  {
    dataIndex: "updated",
    title: "更新时间",
    width: 180,
  },
  {
    dataIndex: "experiment_type_name",
    title: "类型",
    width: 150,
  },
  {
    dataIndex: "experiment_pay_type_name",
    title: "付费性质",
    width: 150,
  },
  {
    dataIndex: "enabled",
    title: "上架状态",
    width: 100,
  },
  // {
  //   dataIndex: "thumb_url",
  //   title: "封面图",
  //   width: 200,
  // },
  {
    dataIndex: "operation",
    title: "操作",
    width: 240,
    align: "center",
    fixed: "right",
  },
]);

const onChange = (page) => {
  console.log(page);
  current.value = page.current;
  pageSize.value = page.pageSize;
  onFinish(formState.value);
};
const current = ref(1);
const pageSize = ref(10);
const pagination = computed(() => ({
  position: ["bottomCenter"],
  // total: tableData.value.length,
  total: response.value.total,
  current: current.value,
  pageSize: pageSize.value,
  showSizeChanger: true,
  size: "large",
  showTotal: (total) => `共 ${total} 条`,
}));

const handleAdd = () => {
  store.setSubTitle("新增虚拟仿真实验");
  router.push("experiment-management-option");
};

const handleDetail = (data) => {
  store.setSubTitle("查看虚拟仿真实验详情");
  router.push("experiment-management-detail?id=" + data.experiment_id);
};
const handleEdit = (data) => {
  console.log("编辑实验", data);
  store.setSubTitle("编辑虚拟仿真实验");
  router.push(`experiment-management-option?id=${data.experiment_id}`);
};

//上架
const handleDelte = (data, enabled) => {
  data.enabled = enabled;
  api.apiExperimentUpdatePost(data);
};

// 清空选择
const clearSelection = () => {
  selectedRowKeys.value = [];
  selectedRows.value = [];
};

// 批量导出功能
const handleExport = async () => {
  if (selectedRowKeys.value.length === 0) {
    message.warning("请先选择要导出的数据");
    return;
  }

  try {
    // 构建导出参数，使用当前搜索条件但限制为选中的数据
    const exportParams = {
      current: current.value,
      pageSize: pageSize.value,
      experiment_ids: selectedRowKeys.value,
    };

    // 只有当字段有值时才添加到参数中
    if (formState.value.name) {
      exportParams.keyword = formState.value.name;
    }
    if (
      formState.value.experiment_category_idArray &&
      formState.value.experiment_category_idArray.length > 0
    ) {
      exportParams.experiment_category_idArray =
        formState.value.experiment_category_idArray;
    }
    if (
      formState.value.experiment_type_idArray &&
      formState.value.experiment_type_idArray.length > 0
    ) {
      exportParams.experiment_type_idArray =
        formState.value.experiment_type_idArray;
    }
    if (
      formState.value.experiment_status_idArray &&
      formState.value.experiment_status_idArray.length > 0
    ) {
      exportParams.experiment_status_idArray =
        formState.value.experiment_status_idArray;
    }
    if (
      formState.value.experiment_pay_type_idArray &&
      formState.value.experiment_pay_type_idArray.length > 0
    ) {
      exportParams.experiment_pay_type_idArray =
        formState.value.experiment_pay_type_idArray;
    }
    if (formState.value.dateRange && formState.value.dateRange.length === 2) {
      exportParams.startDate = formState.value.dateRange[0];
      exportParams.endDate = formState.value.dateRange[1];
    }

    console.log("批量导出参数:", exportParams);

    // 调用导出API
    const response = await AP.ExperimentExport(exportParams);

    console.log("导出响应:", response);

    if (response && response.file) {
      const fileData = response.file;

      // 处理Base64编码的文件内容
      const base64Content = fileData.fileContents;
      const contentType =
        fileData.contentType ||
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
      const fileName = fileData.fileDownloadName || "实验列表_导出.xlsx";

      try {
        // 将Base64字符串转换为二进制数据
        const binaryString = atob(base64Content);
        const bytes = new Uint8Array(binaryString.length);
        for (let i = 0; i < binaryString.length; i++) {
          bytes[i] = binaryString.charCodeAt(i);
        }

        // 创建Blob对象
        const blob = new Blob([bytes], { type: contentType });

        // 创建下载链接
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement("a");
        link.href = url;
        link.download = fileName;

        // 触发下载
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);

        // 清理URL对象
        window.URL.revokeObjectURL(url);

        message.success("导出成功");
      } catch (decodeError) {
        console.error("文件解码失败:", decodeError);
        message.error("文件解码失败，请稍后重试");
      }
    } else {
      const errorMessage = response?.errors?.[0] || "导出失败";
      console.error("导出失败:", response);
      message.error(errorMessage);
    }
  } catch (error) {
    console.error("导出实验列表失败:", error);
    message.error("导出失败，请稍后重试");
  } finally {
  }
};

// 一键彻底删除下架实验
const handleDeleteOfflineExperiments = async () => {
  try {
    // 显示确认对话框
    Modal.confirm({
      title: "确认删除",
      content:
        "此操作将永久删除所有下架状态（enabled=false）的实验及其相关数据，且无法恢复！请确认是否继续？",
      okText: "确认删除",
      cancelText: "取消",
      okType: "danger",
      centered: true,
      onOk: async () => {
        deleteLoading.value = true;

        try {
          // 调用删除下架实验的API
          const response =
            await api.apiExperimentDeleteOfflineExperimentsPost();

          if (response && response.data !== undefined) {
            const deletedCount = response.data;
            message.success(`成功删除 ${deletedCount} 个下架实验及其相关数据`);

            // 刷新表格数据
            onFinish(formState.value);
          } else {
            message.error("删除操作失败，请稍后重试");
          }
        } catch (error) {
          console.error("删除下架实验失败:", error);
          message.error("删除操作失败，请稍后重试");
        } finally {
          deleteLoading.value = false;
        }
      },
    });
  } catch (error) {
    console.error("删除下架实验失败:", error);
    message.error("删除操作失败，请稍后重试");
  }
};
</script>
<style lang="less" scoped>
.list-pages {
  height: 100%;
  padding: 0 16px;
  display: flex;
  flex-direction: column;

  .search-box {
    display: flex;
    align-items: center;
    padding: 18px 0;
    flex-wrap: wrap;
    border-bottom: 1px solid #e5e7eb;

    .search-select {
      width: 120px;
    }

    .line {
      width: 1px;
      height: 16px;
      margin: 0 12px;
      background: #bec4ca;

      @media screen and (max-width: 768px) {
        display: none;
      }
    }

    .search-input-box {
      flex: 1;
      display: flex;
      align-items: center;

      @media screen and (max-width: 768px) {
        width: 100%;
        margin-top: 16px;
        justify-content: space-between;
      }
    }

    .search-input {
      flex: 1;
    }

    .search-btn {
      width: 60px;
      height: 32px;
      background: #2776ff;
      border-radius: 4px;
      font-family: PingFangSC-Regular;
      font-weight: 400;
      font-size: 14px;
      color: #ffffff;
      text-align: center;
      line-height: 32px;
    }
  }

  .table-wrapper {
    width: 100%;
    flex: 1;
    overflow: hidden;

    .table-box {
      height: 100%;
    }
  }

  .list-box {
    width: 100%;
    box-sizing: border-box;
    padding-top: 16px;
    overflow: auto;
    display: grid;
    gap: 16px;
    margin: 0 auto;
    grid-template-columns: repeat(auto-fill, minmax(261px, 1fr));
    justify-content: space-between;

    .list-item {
      width: 261px;
      background: #ffffff;
      border: 1px solid #e6ebf1;
      border-radius: 8px;
      box-sizing: border-box;
      padding: 8px;
      margin: auto;
      position: relative;
      cursor: pointer;

      &:hover {
        border: 1px solid #2776ff;
        box-shadow: 12px 12px 12px 0px rgba(39, 118, 255, 0.1);
      }

      .item-collect {
        position: absolute;
        top: 0;
        right: 0;
        cursor: pointer;
        width: 32px;
        height: 32px;
        background: rgba(0, 0, 0, 0.4) url(@/assets/icon-collet.png) no-repeat
          center center;
        border-radius: 0 8px 0 12px;

        &.cur {
          background: #ffffff url(@/assets/icon-collet-cur.png) no-repeat center
            center;
          border-radius: 0 8px 0 12px;
        }
      }

      .list-img {
        width: 245px;
        height: 249px;
        background: #f3f3f3;
        border: 1px solid #e6ebf1;
        border-radius: 8px;
        box-sizing: border-box;

        img {
          width: 100%;
          height: 100%;
          border-radius: 8px;
        }
      }

      .list-content {
        padding: 14px 0 6px;
        display: flex;
        flex-direction: column;

        .content-title {
          font-family: PingFangSC-Medium;
          font-weight: 500;
          font-size: 16px;
          color: #31323a;
          margin-bottom: 10px;
          line-height: 24px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .content-col {
          display: flex;
          align-items: center;
          justify-content: space-between;

          .col-user {
            display: flex;
            align-items: center;

            .user-img {
              width: 26px;
              height: 26px;
              border-radius: 50%;
            }

            .user-name {
              font-family: PingFangSC, PingFang SC;
              font-weight: 400;
              font-size: 12px;
              color: #262626;
              line-height: 16px;
              text-align: left;
              font-style: normal;
            }
          }

          .col-date {
            font-family: PingFangSC, PingFang SC;
            font-weight: 400;
            font-size: 12px;
            color: #8c8c8c;
            line-height: 16px;
            text-align: center;
            font-style: normal;
          }
        }
      }
    }
  }

  .pagination-box {
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
